
#include "webrtcwidget.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QVBoxLayout>
#include <QProcess>
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>
#include "MainWindow.h"
#include <QThread>
#include "MessageBox.h"
#include "models/operatelogmodel.h"
#include "public/public.h"
#include <models/imagemodel.h>
#include <models/videomodel.h>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include "public/public.h"

#ifdef Q_OS_ANDROID
#include "androidwebview.h"
#else
#include "desktopwebview.h"
#include <QWebEngineSettings>
#include <QWebEnginePage>
#endif


WebRTCBridge::WebRTCBridge(QObject *parent)
    : QObject(parent)
    , networkManager(new QNetworkAccessManager(this))
{
}

WebRTCBridge::~WebRTCBridge()
{
    if(networkManager)
        networkManager->deleteLater();
}

void WebRTCBridge::sendOffer(const QString &offer)
{
    if (m_serverUrl.isEmpty()) {
        return;
    }

    // 创建网络请求
    QNetworkRequest request;
    request.setUrl(QUrl(m_serverUrl));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = networkManager->post(request, offer.toUtf8());

    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            QString response = QString::fromUtf8(reply->readAll());
            qDebug() << "Server response:" << response;
            emit offerResponse(response);
        } else {
            qDebug() << "Network error:" << reply->errorString();
            updateConnectionState("failed");
        }
        reply->deleteLater();
    });

    connect(reply, &QNetworkReply::sslErrors, this, [](const QList<QSslError> &errors) {
        qDebug() << "SSL errors:" << errors;
    });
}

void WebRTCBridge::updateConnectionState(const QString &state)
{
    try {
        emit connectionStateChanged(state);
    } catch (const std::exception& e) {
        qDebug() << "Exception in updateConnectionState:" << e.what();
    }
}

void WebRTCBridge::saveRecording(const QString &base64Data)
{
    // 解码 base64 数据并写入文件
    if(m_recordingFile)
    {
        QByteArray data = QByteArray::fromBase64(base64Data.toLatin1());
        if (m_recordingFile->write(data) == -1) {
            emit recordingError(tr("写入录制数据失败"));
            m_recordingFile->close();
            delete m_recordingFile;
            m_recordingFile = nullptr;
            return;
        }
        // 立即刷新文件缓冲区
        m_recordingFile->flush();
    }
}

void WebRTCBridge::startRecording()
{
    if (!m_recordingFile) {
        // 创建新的录制文件
        m_currentRecordingPath = getVideoPath() + QDateTime::currentDateTime().toString("yyyyMMddhhmmss")+".webm";
        m_recordingFile = new QFile(m_currentRecordingPath);

        if (!m_recordingFile->open(QIODevice::WriteOnly)) {
            emit recordingError(tr("无法创建录制文件"));
            delete m_recordingFile;
            m_recordingFile = nullptr;
            return;
        }
    }
}

void WebRTCBridge::stopRecording()
{
    if (m_recordingFile) {
        m_recordingFile->close();
        delete m_recordingFile;
        m_recordingFile = nullptr;
        emit recordingSaved(m_currentRecordingPath);
    }
}



WebRTCWidget::WebRTCWidget(QWidget *parent)
    : VideoBase(parent)
    // ,VideoBase()
    , m_pWebView(NULL)
{
    // 设置背景为黑色（在初始化时就设置）
    setAttribute(Qt::WA_StyledBackground, true);  // 允许 Widget 使用样式表设置背景
    setStyleSheet(" background-color: rgb(0, 0, 0);border: 0px; ");
    initWebView();         // 初始化 WebView
    setupConnections();    // 最后设置连接
}



void WebRTCWidget::initWebView()
{
    //#ifdef 1
    m_pWebView = new DesktopWebView(this);
    // #else
    //     m_pWebView = new AndroidWebView(this);
    // #endif
    m_pWebView->setStyleSheet("background-color: rgb(0, 0, 0);");

    m_pWebrtcBridge = new WebRTCBridge(this);
    m_pWebView->addJavaScriptObject("m_pWebrtcBridge", m_pWebrtcBridge);
    layout()->addWidget(m_pWebView);
    m_pWebView->hide();
    m_pMask = new QLabel(this);
    m_pMask->setStyleSheet("QLabel{"
                           "background-color:transparent;"
                           "}");

}


void WebRTCWidget::onLoadFinished(bool ok)
{
    if (ok) {
        QTimer::singleShot(500, this, [this]() {
            // 检查 webrtcPlayer 是否已初始化
            m_pWebView->evaluateJavaScript(
                "typeof window.webrtcPlayer !== 'undefined'",
                [this](const QVariant &result) {
                    if (result.toBool()) {
                        // webrtcPlayer 已初始化，执行播放
                        m_pWebView->evaluateJavaScript(
                            "window.webrtcPlayer.play();",
                            [](const QVariant &result) {
                                Q_UNUSED(result)
                            }
                            );
                    } else {
                        qWarning() << "webrtcPlayer not initialized yet";
                    }
                });
        });
    } else {
        qWarning() << "Failed to load WebRTC page";
    }
}

void WebRTCWidget::resizeEvent(QResizeEvent *event)
{
    if(m_pMask) //最大化时按钮显示在右侧
        m_pMask->setGeometry(0,0,width(),height());
    VideoBase::resizeEvent(event);
}



void WebRTCWidget::setUrl(QString strUrl)
{
    if(m_pWebrtcBridge)
        m_pWebrtcBridge->setServerUrl(strUrl +"/offer");
    VideoBase::setUrl(strUrl);
}


void WebRTCWidget::setupConnections()
{
    // 连接 WebRTC Bridge 的信号
    connect(m_pWebrtcBridge, &WebRTCBridge::connectionStateChanged, this, [this](const QString &state) {
        if(state == "connecting")
        {
            m_pWebView->hide();
            onConnecting();
        }
        else if (state == "connected") {
            m_pWebView->show();
            onConnectSucc();
        } else if (state == "failed" || state == "disconnected") {
            m_pWebView->hide();
            if(isRecording())
            {
                if (m_pWebrtcBridge) {
                    m_pWebrtcBridge->stopRecording();
                }
            }
            onConnectFail();
        }
    });

    // 连接录制相关的信号
    connect(m_pWebrtcBridge, &WebRTCBridge::recordingSaved, this, [this](const QString &filePath) {
        qDebug() << "录制文件已保存:" << filePath;
        onRecordEnd(filePath);
    });

    connect(m_pWebrtcBridge, &WebRTCBridge::recordingError, this, [](const QString &error) {
        qWarning() << "录制错误:" << error;
    });
}


void WebRTCWidget::stopVideo(bool bSync)
{
    // 如果正在录制，先停止录制
    if (m_bRecording) {
        stopRecording(bSync);
    }

    if (m_pWebView) {
        if (bSync) {
            m_pWebView->syncJavaScript("window.webrtcPlayer.stop();");
        } else {
            m_pWebView->evaluateJavaScript(
                "window.webrtcPlayer.stop();",
                [](const QVariant &result) {
                    Q_UNUSED(result)
                }
                );
        }
        m_pWebView->stop();
    }

    // 重置状态
    if (m_pStatusLabel)
        m_pStatusLabel->setText("");
    if(m_pStatusContainer)
        m_pStatusContainer->show();
    if(m_pReconnectButton)
        m_pReconnectButton->hide();
    if(m_pWebView)
        m_pWebView->hide();

    m_bPlaying = false;
}

void WebRTCWidget::takePhoto()
{
    if (!m_pWebView || !m_pWebView->isVisible()) {
        return;
    }

    // 获取视频元素的截图
    m_pWebView->evaluateJavaScript(
        "(() => {"
        "    const video = document.getElementById('video');"
        "    if (!video) return null;"
        "    const canvas = document.createElement('canvas');"
        "    canvas.width = video.videoWidth;"
        "    canvas.height = video.videoHeight;"
        "    const ctx = canvas.getContext('2d');"
        "    ctx.drawImage(video, 0, 0);"
        "    return canvas.toDataURL('image/png');"
        "})();",
        [this](const QVariant &result) {
            if (result.isNull()) {
                OPERATE_LOG("截图失败：无法获取视频画面");
                return;
            }

            QString dataUrl = result.toString();
            if (dataUrl.startsWith("data:image/png;base64,")) {
                // 移除 data URL 前缀
                QString base64Data = dataUrl.mid(22);
                QByteArray imageData = QByteArray::fromBase64(base64Data.toLatin1());

                QImage img;
                if (img.loadFromData(imageData, "PNG")) {
                    QString filePath = getPhotoPath() + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".png";
                    if(!img.save(filePath)) {
                        warning(parentWidget(), tr("图片保存失败"));
                        OPERATE_LOG("截图失败：图片保存失败");
                        return;
                    }
                    else
                    {
                        onTakePhoto(filePath);
                        OPERATE_LOG("截图成功");
                    }
                }
            }
        }
        );
}

bool WebRTCWidget::startRecording()
{
    if (!m_pWebView || !m_pWebView->isVisible() ) {
        return false;
    }

    // 开始录制
    m_pWebView->evaluateJavaScript(
        "window.webrtcPlayer.startRecording();",
        [this](const QVariant &result) {
            m_bRecording = result.toBool();
            if (!isRecording()) {
                warning(MainWindow::getInstance(),"开始录制失败");
                OPERATE_LOG("开始录制视频失败");
            }
            else
            {
                if (m_pWebrtcBridge) {
                    m_pWebrtcBridge->startRecording();
                    m_pVideoBtn->setStyleSheet(
                        "QPushButton{ "
                        "  background-color:transparent;"
                        "   border-image: url(:/images/video_record_2.png); "
                        "} ");

                    m_pRecordLab->setText("00:00:00");
                    m_pRecordTimer->start(1000);

                    OPERATE_LOG("开始录制视频");
                }
            }
        }
        );

    return true;
}

bool WebRTCWidget::stopRecording(bool bSync)
{
    if (!m_bRecording) {
        return false;
    }
    // 调用 WebRTCBridge 的 stopRecording 方法
    if (m_pWebrtcBridge) {
        m_pWebrtcBridge->stopRecording();
    }
    if(bSync)
    {
        m_pWebView->syncJavaScript("stopRecording()");
    }
    else
    {
        // 调用 JavaScript 停止录制
        m_pWebView->evaluateJavaScript("stopRecording()", [](const QVariant& result) {
            Q_UNUSED(result)
        });
    }

    m_bRecording = false;
    m_pVideoBtn->setStyleSheet(
        "QPushButton{ "
        "  background-color:transparent;"
        "   border-image: url(:/images/video_record.png); "
        "} "
        "QPushButton:pressed{"
        "  border-image: url(:/images/video_record_pressed.png);"
        "}");
    m_pRecordLab->setText("");
    if(m_pRecordTimer)
        m_pRecordTimer->stop();
    m_nRecordSeconds = 0;
    OPERATE_LOG("停止录制视频");
    return true;
}

WebRTCWidget::~WebRTCWidget()
{
    // 先停止视频播放
    stopVideo(true);
    // 清理 WebRTC Bridge
    if (m_pWebrtcBridge) {
        delete m_pWebrtcBridge;  // 直接删除
        m_pWebrtcBridge = nullptr;
    }

    // 清理 WebView
    if (m_pWebView) {
        m_pWebView->stop();  // 使用抽象接口的 stop 方法
        delete m_pWebView;   // 直接删除 WebView
        m_pWebView = nullptr;
    }
}

void WebRTCWidget::startPlay()
{
    if(m_strUrl.length() > 0)
    {
        // 初始化 WebView
        if (m_pWebView) {
            m_pWebView->setUrl(QUrl("qrc:///view/webrtc/webrtc.html"));
            connect(m_pWebView, &AbstractWebView::loadFinished, this,  &WebRTCWidget::onLoadFinished,Qt::UniqueConnection);
        } else
        {
            qWarning() << "WebView is null";
        }
        m_nTestCount++;
        m_bPlaying = true;
        if (m_pReconnectTimer) {
            m_pReconnectTimer->stop();
        }
    }
}

void WebRTCWidget::setMute(bool bMute)
{
    if (m_pWebView) {
        m_pWebView->evaluateJavaScript(
            QString("window.webrtcPlayer.setMute(%1);").arg(bMute ? "true" : "false"),
            [](const QVariant &result) {
                Q_UNUSED(result)
            }
            );
    } 
}
